package com.steakliu.algorithm;

/**
 * 功能说明：
 * <p>
 * Original @Author: steakliu-刘牌, 2022-08-29  23:25
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
public class AddTwoNumbers {
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(2);
        ListNode listNode2 = new ListNode(4);
        ListNode listNode3 = new ListNode(3);
        listNode1.next = listNode2;
        listNode2.next = listNode3;

        ListNode listNode4 = new ListNode(5);
        ListNode listNode5 = new ListNode(6);
        ListNode listNode6 = new ListNode(4);
        listNode4.next = listNode5;
        listNode5.next = listNode6;
        solution(listNode1, listNode4);

    }

    private static void solution(ListNode l1, ListNode l2) {
        ListNode nextNode = new ListNode(0);
        ListNode currNode = nextNode;
        int carry = 0; // 进位
        while (l1 != null || l2 != null) {
            int carryTotal = l1.val + l2.val; //位和
            if (carryTotal > 10) { //大于10 进位
                carry = 1;
                carryTotal = (carryTotal + carry) % 10;
            }
            if (carryTotal == 10){
                carryTotal = 0;
            }
            currNode.val = carryTotal;
            currNode.next = nextNode;
            l1 = l1.next;
            l2 = l2.next;
        }
        System.out.println(currNode);
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode(0);
        ListNode cur = pre;
        int carry = 0;
        while(l1 != null || l2 != null) {
            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            int sum = x + y + carry;

            carry = sum / 10;
            sum = sum % 10;
            cur.next = new ListNode(sum);

            cur = cur.next;
            if(l1 != null)
                l1 = l1.next;
            if(l2 != null)
                l2 = l2.next;
        }
        if(carry == 1) {
            cur.next = new ListNode(carry);
        }
        return pre.next;
    }
}
